import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/chunk_upload.dart';
import '../services/upload/chunk_upload_service.dart';
import '../services/upload/core/upload_manager.dart';
import '../riverpod/photo_backup_notifier.dart'; // 导入相册备份提供者
import 'dart:io';
import 'upload_detail_page.dart'; // 导入上传详情页面
import 'dart:math' as Math;
import '../services/asset_cache_service.dart'; // 添加资产缓存服务导入
import 'package:photo_manager/photo_manager.dart'; // 添加photo_manager库导入
import '../services/photo_backup_service.dart'; // 添加照片备份服务导入

class TransferListPage extends ConsumerStatefulWidget {
  const TransferListPage({Key? key}) : super(key: key);

  @override
  ConsumerState<TransferListPage> createState() => _TransferListPageState();
}

class _TransferListPageState extends ConsumerState<TransferListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final UploadManager _uploadManager = UploadManager();
  Key _activeStreamKey = UniqueKey();
  Key _completedStreamKey = UniqueKey();
  int _selectedTabIndex = 1; // 默认选中上传标签页

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 4,
      vsync: this,
      initialIndex: _selectedTabIndex,
    );

    // 使用AnimationListener而不是TabListener直接处理索引变化
    _tabController.animation!.addListener(() {
      final indexChange = _tabController.animation!.value.round();
      if (indexChange != _selectedTabIndex) {
        setState(() {
          _selectedTabIndex = indexChange;
        });
      }
    });

    // 设置上传任务完成监听
    _setupUploadCompletionListener();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 清空已上传文件记录
  void _clearCompletedTasks() {
    ChunkUploadService.clearCompletedTasks();
    setState(() {
      _completedStreamKey = UniqueKey();
    });
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('已清空')));
  }

  // 打开最高备份数设置对话框
  void _showMaxConcurrentUploadsDialog() {
    // 获取当前并发上传数
    final currentCount = ref.read(photoBackupProvider).parallelBackupCount;

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.only(top: 10, bottom: 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 底部滑块指示器
              Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey.shade300,
                  borderRadius: BorderRadius.circular(2),
                ),
                margin: const EdgeInsets.only(bottom: 10),
              ),
              // 标题
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 10),
                child: Text(
                  '选择并行备份的文件数',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              // 选项
              _buildBottomSheetOption(3, currentCount),
              _buildBottomSheetOption(5, currentCount),
              _buildBottomSheetOption(10, currentCount),
            ],
          ),
        );
      },
    );
  }

  // 构建底部抽屉选项
  Widget _buildBottomSheetOption(int count, int currentCount) {
    return InkWell(
      onTap: () {
        ref.read(photoBackupProvider.notifier).setParallelBackupCount(count);
        Navigator.pop(context);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '最高$count个文件',
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w500,
                color: currentCount == count ? Colors.blue : Colors.black87,
              ),
            ),
            if (currentCount == count)
              const Icon(Icons.check, color: Colors.blue, size: 20),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 监听并发上传数变化
    final parallelBackupCount =
        ref.watch(photoBackupProvider).parallelBackupCount;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '传输列表',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          // 添加调试按钮
          IconButton(
            icon: const Icon(Icons.bug_report),
            onPressed: _showDebugOptions,
            tooltip: '调试选项',
          ),
          // 添加全部暂停/继续按钮
          StreamBuilder<List<UploadTask>>(
            stream: ChunkUploadService.uploadTasksStream,
            initialData: ChunkUploadService.uploadTasks,
            builder: (context, snapshot) {
              if (!snapshot.hasData || snapshot.data!.isEmpty) {
                return const SizedBox.shrink(); // 没有上传任务时不显示按钮
              }

              final tasks = snapshot.data!;
              final hasActiveTasks = tasks.any(
                (task) =>
                    task.status == UploadTaskStatus.uploading ||
                    task.status == UploadTaskStatus.pending,
              );
              final hasPausedTasks = tasks.any(
                (task) => task.status == UploadTaskStatus.paused,
              );

              // 如果没有活动或暂停的任务，不显示按钮
              if (!hasActiveTasks && !hasPausedTasks) {
                return const SizedBox.shrink();
              }

              return IconButton(
                icon: Icon(
                  hasActiveTasks
                      ? Icons.pause_circle_outline
                      : Icons.play_circle_outline,
                  color: hasActiveTasks ? Colors.blue : Colors.green,
                ),
                onPressed: () {
                  final photoBackupService = PhotoBackupService();
                  if (hasActiveTasks) {
                    photoBackupService.pauseAllUploads();
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('已暂停所有上传任务')));
                  } else if (hasPausedTasks) {
                    photoBackupService.resumeAllUploads();
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('已恢复所有上传任务')));
                  }
                  setState(() {
                    _activeStreamKey = UniqueKey();
                  });
                },
                tooltip: hasActiveTasks ? '暂停所有上传' : '恢复所有上传',
              );
            },
          ),
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              // 打开SVIP加速介绍
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('SVIP加速功能，享受更快传输速度')),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          Container(
            color: Colors.green[50],
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Row(
              children: [
                const Icon(Icons.security, color: Colors.green, size: 18),
                const SizedBox(width: 8),
                const Text(
                  '咕噜酱会守护你的传输安全',
                  style: TextStyle(
                    color: Colors.green,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const Spacer(),
                const Icon(Icons.chevron_right, color: Colors.green, size: 18),
              ],
            ),
          ),
          // 顶部标签栏
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
            ),
            child: TabBar(
              controller: _tabController,
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              indicatorColor: Colors.blue,
              indicatorSize: TabBarIndicatorSize.label,
              labelStyle: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
              unselectedLabelStyle: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
              tabs: const [
                Tab(icon: Icon(Icons.download), text: '下载'),
                Tab(icon: Icon(Icons.upload), text: '上传'),
                Tab(icon: Icon(Icons.save), text: '转存'),
                Tab(icon: Icon(Icons.cloud_upload), text: '云添加'),
              ],
            ),
          ),
          // 标签页内容
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildDownloadContent(), // 下载标签页
                _buildUploadContent(), // 上传标签页
                _buildTransferContent(), // 转存标签页
                _buildCloudAddContent(), // 云添加标签页
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 自动备份设置组件
  Widget _buildAutoBackupSetting() {
    // 使用全局状态的parallelBackupCount
    final parallelBackupCount =
        ref.watch(photoBackupProvider).parallelBackupCount;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              const Icon(Icons.backup, color: Colors.grey, size: 16),
              const SizedBox(width: 8),
              const Text(
                '自动备份',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          Row(
            children: [
              const Text(
                '最高备份数：',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: Colors.black87,
                ),
              ),
              GestureDetector(
                onTap: _showMaxConcurrentUploadsDialog,
                child: Row(
                  children: [
                    Text(
                      '$parallelBackupCount',
                      style: const TextStyle(
                        color: Colors.blue,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const Icon(Icons.arrow_drop_down, color: Colors.blue),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 下载标签页内容
  Widget _buildDownloadContent() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.download_done, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('暂无下载任务', style: TextStyle(color: Colors.grey.shade600)),
        ],
      ),
    );
  }

  // 上传标签页内容
  Widget _buildUploadContent() {
    // 获取选中相册的总文件数
    final backupState = ref.watch(photoBackupProvider);
    int totalFilesToBackup = 0;

    // 计算选中相册的文件总数
    for (var album in backupState.albumCache) {
      // 检查该相册是否被选中
      if (backupState.selectedAlbums[album.id] == true) {
        // 根据用户选择计算有效文件数
        totalFilesToBackup += album.getValidCount(
          backupState.autoBackupPhotos,
          backupState.autoBackupVideos,
        );
      }
    }

    return StreamBuilder<List<UploadTask>>(
      key: _activeStreamKey,
      stream: ChunkUploadService.uploadTasksStream,
      initialData: ChunkUploadService.uploadTasks,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Center(child: Text('加载错误: ${snapshot.error}'));
        }

        // 筛选并排序任务
        final tasks =
            snapshot.hasData
                ? List<UploadTask>.from(snapshot.data!)
                : <UploadTask>[];
        final activeTasks =
            tasks
                .where(
                  (task) =>
                      task.status == UploadTaskStatus.pending ||
                      task.status == UploadTaskStatus.uploading ||
                      task.status == UploadTaskStatus.paused ||
                      task.status == UploadTaskStatus.failed,
                )
                .toList();

        final completedTasks =
            tasks
                .where(
                  (task) =>
                      task.status == UploadTaskStatus.completed ||
                      task.status == UploadTaskStatus.canceled,
                )
                .toList();

        // 计算剩余备份数量（总数减去正在上传的和已完成的）
        int remainingCount = totalFilesToBackup - completedTasks.length;
        if (remainingCount < 0) remainingCount = 0;

        // 检查是否有正在上传的任务
        final hasActiveTasks = activeTasks.any(
          (task) =>
              task.status == UploadTaskStatus.uploading ||
              task.status == UploadTaskStatus.pending,
        );

        // 检查是否有暂停的任务
        final hasPausedTasks = activeTasks.any(
          (task) => task.status == UploadTaskStatus.paused,
        );

        return Column(
          children: [
            // 自动备份设置 - 直接包含在上传标签页内容中
            _buildAutoBackupSetting(),

            // 上传任务列表
            Expanded(
              child:
                  tasks.isEmpty && totalFilesToBackup == 0
                      ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.cloud_upload,
                              size: 64,
                              color: Colors.grey.shade400,
                            ),
                            const SizedBox(height: 16),
                            Text(
                              '暂无上传任务',
                              style: TextStyle(color: Colors.grey.shade600),
                            ),
                          ],
                        ),
                      )
                      : SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (activeTasks.isNotEmpty ||
                                totalFilesToBackup > 0) ...[
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 16,
                                  vertical: 12,
                                ),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        const Text(
                                          '正在备份',
                                          style: TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black,
                                          ),
                                        ),
                                        // 全部暂停/恢复按钮
                                        if (hasActiveTasks || hasPausedTasks)
                                          IconButton(
                                            icon: Icon(
                                              hasActiveTasks
                                                  ? Icons.pause_circle_outline
                                                  : Icons.play_circle_outline,
                                              color:
                                                  hasActiveTasks
                                                      ? Colors.blue
                                                      : Colors.green,
                                              size: 20,
                                            ),
                                            onPressed: () {
                                              final photoBackupService =
                                                  PhotoBackupService();
                                              setState(() {
                                                if (hasActiveTasks) {
                                                  photoBackupService
                                                      .pauseAllUploads();
                                                } else if (hasPausedTasks) {
                                                  photoBackupService
                                                      .resumeAllUploads();
                                                }
                                                // 更新界面
                                                _activeStreamKey = UniqueKey();
                                              });
                                            },
                                            tooltip:
                                                hasActiveTasks
                                                    ? '全部暂停'
                                                    : '全部继续',
                                            padding: EdgeInsets.zero,
                                            constraints: const BoxConstraints(),
                                          ),
                                      ],
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        _navigateToUploadDetailPage();
                                      },
                                      child: Text(
                                        '剩余 $remainingCount 个',
                                        style: const TextStyle(
                                          color: Colors.blue,
                                          fontSize: 14,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              ...activeTasks.map(
                                (task) => _buildTaskItem(task),
                              ),

                              // 当没有正在上传的任务但有文件需要备份时显示提示
                              if (activeTasks.isEmpty && totalFilesToBackup > 0)
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 16,
                                        vertical: 12,
                                      ),
                                      child: Row(
                                        children: [
                                          Icon(
                                            Icons.info_outline,
                                            color: Colors.grey.shade600,
                                            size: 16,
                                          ),
                                          const SizedBox(width: 8),
                                          Text(
                                            '等待网络连接或自动备份设置开启',
                                            style: TextStyle(
                                              color: Colors.black87,
                                              fontSize: 14,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

                                    // 显示选中相册的概览
                                    _buildAlbumsOverview(backupState),
                                  ],
                                ),
                            ],

                            if (completedTasks.isNotEmpty) ...[
                              // 添加分隔线
                              Divider(color: Colors.grey.shade200, height: 1),
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 16,
                                  vertical: 12,
                                ),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      '已上传(${completedTasks.length})',
                                      style: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.black,
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: _clearCompletedTasks,
                                      child: const Text(
                                        '清空',
                                        style: TextStyle(
                                          color: Colors.blue,
                                          fontSize: 14,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              ...completedTasks
                                  .take(5)
                                  .map((task) => _buildCompletedTaskItem(task)),
                            ],

                            // 底部padding
                            const SizedBox(height: 10),

                            // 添加网盘空间占位
                            if (totalFilesToBackup > 0 ||
                                completedTasks.isNotEmpty)
                              _buildDiskSpaceIndicator(),
                          ],
                        ),
                      ),
            ),
          ],
        );
      },
    );
  }

  // 网盘空间指示器（占位）
  Widget _buildDiskSpaceIndicator() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          Text(
            '网盘总空间: 487GB/1.0TB',
            style: TextStyle(
              color: Colors.black87,
              fontSize: 13,
              fontWeight: FontWeight.w500,
            ),
          ),
          const Spacer(),
          Text(
            '查看详情 >',
            style: TextStyle(
              color: Colors.blue,
              fontSize: 13,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 转存标签页内容
  Widget _buildTransferContent() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.save, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('暂无转存任务', style: TextStyle(color: Colors.grey.shade600)),
        ],
      ),
    );
  }

  // 云添加标签页内容
  Widget _buildCloudAddContent() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.cloud_upload, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('暂无云添加任务', style: TextStyle(color: Colors.grey.shade600)),
          const SizedBox(height: 8),
          Text(
            '添加磁力链接、BT种子等远程下载',
            style: TextStyle(color: Colors.grey.shade400, fontSize: 12),
          ),
        ],
      ),
    );
  }

  // 构建任务项
  Widget _buildTaskItem(UploadTask task) {
    final bool isUploading = task.status == UploadTaskStatus.uploading;
    final bool isPaused = task.status == UploadTaskStatus.paused;
    final bool isPending = task.status == UploadTaskStatus.pending;
    final bool isFailed = task.status == UploadTaskStatus.failed;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          _getFileTypeIcon(task.fileName),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  task.fileName,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                    color: Colors.black87,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Text(
                      '${task.formattedSize}',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w400,
                        color: Colors.black54,
                      ),
                    ),
                    if (isUploading) ...[
                      const SizedBox(width: 8),
                      Text(
                        '上传中 ${task.progress.toInt()}%',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w500,
                          color: Colors.blue[600],
                        ),
                      ),
                    ],
                    if (isPaused) ...[
                      const SizedBox(width: 8),
                      Text(
                        '已暂停',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w500,
                          color: Colors.orange[600],
                        ),
                      ),
                    ],
                    if (isPending) ...[
                      const SizedBox(width: 8),
                      Text(
                        '等待中',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w500,
                          color: Colors.black54,
                        ),
                      ),
                    ],
                    if (isFailed) ...[
                      const SizedBox(width: 8),
                      Text(
                        '上传失败',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w500,
                          color: Colors.red[600],
                        ),
                      ),
                    ],
                  ],
                ),
                if (isUploading || isPending)
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 4),
                      // 添加分片上传信息
                      if (task.type == UploadTaskType.chunk &&
                          task.totalChunks != null)
                        Text(
                          '分片: ${task.uploadedChunks ?? 0}/${task.totalChunks}',
                          style: TextStyle(
                            fontSize: 11,
                            fontWeight: FontWeight.w500,
                            color: Colors.black54,
                          ),
                        ),
                      const SizedBox(height: 4),
                      LinearProgressIndicator(
                        value: isUploading ? task.progress / 100 : 0.0,
                        backgroundColor: Colors.grey[200],
                        valueColor: AlwaysStoppedAnimation<Color>(
                          isPending ? Colors.grey : Colors.blue,
                        ),
                      ),
                      if (isFailed && task.error != null)
                        Padding(
                          padding: const EdgeInsets.only(top: 4),
                          child: Text(
                            task.error!,
                            style: TextStyle(
                              fontSize: 11,
                              fontWeight: FontWeight.w500,
                              color: Colors.red[500],
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                    ],
                  ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          if (isPaused)
            IconButton(
              icon: const Icon(Icons.play_arrow, color: Colors.blue),
              onPressed: () {
                ChunkUploadService.resumeUploadTask(task.id);
              },
              tooltip: '继续',
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(),
              iconSize: 24,
            )
          else if (isUploading)
            IconButton(
              icon: const Icon(Icons.pause, color: Colors.blue),
              onPressed: () {
                ChunkUploadService.pauseUploadTask(task.id);
              },
              tooltip: '暂停',
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(),
              iconSize: 24,
            )
          else if (isFailed)
            IconButton(
              icon: const Icon(Icons.refresh, color: Colors.blue),
              onPressed: () {
                // 目前没有retryUploadTask方法，使用removeUploadTask然后重新添加文件
                ChunkUploadService.removeUploadTask(task.id);
                // 向用户提示需要重新选择文件上传
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(const SnackBar(content: Text('请重新选择文件上传')));
              },
              tooltip: '重试',
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(),
              iconSize: 24,
            ),
        ],
      ),
    );
  }

  // 构建已完成任务项
  Widget _buildCompletedTaskItem(UploadTask task) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          _getFileTypeIcon(task.fileName),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  task.fileName,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                    color: Colors.black87,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  '${task.formattedSize} · ${_getStatusText(task.status)}',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w400,
                    color: Colors.black54,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          IconButton(
            icon: const Icon(Icons.close, color: Colors.grey),
            onPressed: () {
              ChunkUploadService.removeUploadTask(task.id);
            },
            tooltip: '删除',
          ),
        ],
      ),
    );
  }

  // 获取文件类型图标
  Widget _getFileTypeIcon(String fileName) {
    final extension = fileName.split('.').last.toLowerCase();

    IconData iconData;
    Color iconColor;

    switch (extension) {
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        iconData = Icons.image;
        iconColor = Colors.blue;
        break;
      case 'pdf':
        iconData = Icons.picture_as_pdf;
        iconColor = Colors.red;
        break;
      case 'doc':
      case 'docx':
        iconData = Icons.description;
        iconColor = Colors.blue[700]!;
        break;
      case 'xls':
      case 'xlsx':
        iconData = Icons.table_chart;
        iconColor = Colors.green;
        break;
      case 'mp3':
      case 'wav':
      case 'ogg':
        iconData = Icons.music_note;
        iconColor = Colors.purple;
        break;
      case 'mp4':
      case 'avi':
      case 'mov':
        iconData = Icons.video_file;
        iconColor = Colors.orange;
        break;
      default:
        iconData = Icons.insert_drive_file;
        iconColor = Colors.grey;
    }

    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        color: iconColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Icon(iconData, color: iconColor, size: 24),
    );
  }

  String _getStatusText(UploadTaskStatus status) {
    switch (status) {
      case UploadTaskStatus.pending:
        return '等待上传';
      case UploadTaskStatus.uploading:
        return '上传中';
      case UploadTaskStatus.paused:
        return '已暂停';
      case UploadTaskStatus.completed:
        return '上传成功';
      case UploadTaskStatus.failed:
        return '上传失败';
      case UploadTaskStatus.canceled:
        return '已取消';
      default:
        return '未知状态';
    }
  }

  // 构建选中相册概览
  Widget _buildAlbumsOverview(PhotoBackupState backupState) {
    // 过滤出被选中的相册
    final selectedAlbumInfos =
        backupState.albumCache
            .where((album) => backupState.selectedAlbums[album.id] == true)
            .toList();

    // 如果没有选中的相册，返回空容器
    if (selectedAlbumInfos.isEmpty) {
      return Container();
    }

    // 按照文件数量排序（从高到低）
    selectedAlbumInfos.sort((a, b) {
      int aCount = a.getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
      int bCount = b.getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
      return bCount.compareTo(aCount);
    });

    // 计算剩余相册数量和文件数
    int totalCount = selectedAlbumInfos.length;
    int totalRemainingFiles = 0;

    for (var album in selectedAlbumInfos) {
      totalRemainingFiles += album.getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 8),
          // 仅显示标题和查看全部按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '待备份相册',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              GestureDetector(
                onTap: _navigateToPhotoBackupPage,
                child: Text(
                  '查看全部 >',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Colors.blue,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          // 水平滚动列表显示所有选中的相册
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                // 显示前3个相册，缩略图不可点击
                for (int i = 0; i < Math.min(3, selectedAlbumInfos.length); i++)
                  _buildAlbumThumb(selectedAlbumInfos[i], backupState),

                // 只有超过3个相册时才显示剩余相册指示器，且可点击
                if (selectedAlbumInfos.length > 3)
                  _buildMoreAlbumsIndicator(selectedAlbumInfos.length - 3),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建相册缩略图
  Widget _buildAlbumThumb(AlbumInfo album, PhotoBackupState backupState) {
    // 获取相册有效文件数
    final validCount = album.getValidCount(
      backupState.autoBackupPhotos,
      backupState.autoBackupVideos,
    );

    return Container(
      width: 80,
      margin: const EdgeInsets.only(right: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // 相册缩略图 - 不可点击
          Container(
            height: 60,
            width: 80,
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.grey.shade300),
            ),
            child:
                album.thumbnailPath != null
                    ? ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: Image.file(
                        File(album.thumbnailPath!),
                        fit: BoxFit.cover,
                        width: 80,
                        height: 60,
                      ),
                    )
                    : Center(
                      child: Icon(
                        _getAlbumIconData(album.name),
                        color: Colors.grey.shade400,
                        size: 30,
                      ),
                    ),
          ),
          const SizedBox(height: 4),
          // 相册名称
          Container(
            height: 16,
            child: Text(
              album.name,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          // 显示文件数
          Container(
            height: 14,
            child: Text(
              '$validCount个项目',
              style: TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w500,
                color: Colors.black54,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 构建更多相册指示器
  Widget _buildMoreAlbumsIndicator(int moreCount) {
    // 获取当前的备份状态
    final backupState = ref.read(photoBackupProvider);

    // 计算没有显示的相册的文件总数
    int totalRemainingFiles = 0;

    // 过滤选中的相册
    final selectedAlbums =
        backupState.albumCache
            .where((album) => backupState.selectedAlbums[album.id] == true)
            .toList();

    // 按照文件数量排序（从高到低）
    selectedAlbums.sort((a, b) {
      final aCount = a.getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
      final bCount = b.getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
      return bCount.compareTo(aCount);
    });

    // 前3个相册已显示，计算剩余的相册的文件总数
    for (int i = 3; i < selectedAlbums.length; i++) {
      totalRemainingFiles += selectedAlbums[i].getValidCount(
        backupState.autoBackupPhotos,
        backupState.autoBackupVideos,
      );
    }

    return Container(
      width: 80,
      margin: const EdgeInsets.only(right: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // 带有叠层效果的缩略图 - 可点击跳转
          GestureDetector(
            onTap: _navigateToPhotoBackupPage,
            child: Stack(
              children: [
                Container(
                  height: 60,
                  width: 80,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(color: Colors.grey.shade300),
                  ),
                  // 使用剩余相册的第一个缩略图作为背景
                  child:
                      selectedAlbums.length > 3 &&
                              selectedAlbums[3].thumbnailPath != null
                          ? ClipRRect(
                            borderRadius: BorderRadius.circular(6),
                            child: Stack(
                              children: [
                                Image.file(
                                  File(selectedAlbums[3].thumbnailPath!),
                                  fit: BoxFit.cover,
                                  width: 80,
                                  height: 60,
                                ),
                                // 添加半透明叠层
                                Container(
                                  width: 80,
                                  height: 60,
                                  color: Colors.black.withOpacity(0.4),
                                  child: Center(
                                    child: Text(
                                      '+$moreCount',
                                      style: const TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          )
                          : Center(
                            child: Text(
                              '+$moreCount',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                                color: Colors.grey.shade600,
                              ),
                            ),
                          ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 4),
          // 固定高度文本占位 - 不可点击
          Container(
            height: 16,
            child: const Text(
              '剩余相册',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          // 显示剩余文件总数 - 不可点击
          Container(
            height: 14,
            child: Text(
              '$totalRemainingFiles个项目',
              style: TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w500,
                color: Colors.black54,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 根据相册名称获取图标
  IconData _getAlbumIconData(String albumName) {
    final name = albumName.toLowerCase();
    if (name.contains('camera') || name.contains('相机')) {
      return Icons.camera_alt;
    } else if (name.contains('screenshot') || name.contains('截图')) {
      return Icons.screenshot;
    } else if (name.contains('wechat') || name.contains('微信')) {
      return Icons.chat;
    } else {
      return Icons.photo_library;
    }
  }

  // 跳转到上传详情页面
  void _navigateToUploadDetailPage() {
    // 直接导航到上传详情页面，数据加载在页面内部处理
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const UploadDetailPage()),
    );
  }

  // 跳转到相册备份页面
  void _navigateToPhotoBackupPage() {
    Navigator.pushNamed(context, '/photo-backup');
  }

  // 设置上传任务完成监听
  void _setupUploadCompletionListener() {
    ChunkUploadService.uploadTasksStream.listen((tasks) {
      if (!mounted) return;

      // 计算活跃任务数量（上传中或等待中）
      final activeCount =
          tasks
              .where(
                (task) =>
                    task.status == UploadTaskStatus.uploading ||
                    task.status == UploadTaskStatus.pending,
              )
              .length;

      // 检查是否有失败的任务，失败任务不应触发添加新资产
      final failedTasks =
          tasks
              .where((task) => task.status == UploadTaskStatus.failed)
              .toList();

      if (failedTasks.isNotEmpty) {
        // 有失败任务，记录日志但不添加新任务
        for (var task in failedTasks) {
          debugPrint('检测到失败任务: ${task.fileName}, 不添加新资产');
        }
        return;
      }

      // 如果活跃任务数量小于最大并行数，尝试添加新资产到队列
      final photoBackupService = PhotoBackupService();
      if (activeCount < ref.read(photoBackupProvider).parallelBackupCount &&
          photoBackupService.isBackingUp) {
        // 计算需要添加的新资产数量：最大并行数 - 活跃任务数
        final neededCount =
            ref.read(photoBackupProvider).parallelBackupCount - activeCount;

        if (neededCount > 0) {
          debugPrint('传输列表页面：检测到任务完成，尝试添加$neededCount个新资产到队列');
          photoBackupService.addNewAssetsToQueue(ref, neededCount);

          // 刷新UI
          setState(() {
            _activeStreamKey = UniqueKey();
          });
        }
      }
    });
  }

  // 添加调试选项
  void _showDebugOptions() {
    showModalBottomSheet(
      context: context,
      builder:
          (context) => SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: const Icon(
                    Icons.play_circle_filled,
                    color: Colors.green,
                  ),
                  title: const Text('强制刷新任务列表'),
                  subtitle: const Text('手动刷新上传任务状态'),
                  onTap: () {
                    Navigator.pop(context);
                    setState(() {
                      _activeStreamKey = UniqueKey();
                      _completedStreamKey = UniqueKey();
                    });
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('已刷新任务列表')));
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.refresh),
                  title: const Text('重置备份状态'),
                  subtitle: const Text('修复可能的挂起状态'),
                  onTap: () {
                    Navigator.pop(context);
                    final photoBackupService = PhotoBackupService();
                    photoBackupService.resetBackupStatus();
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('备份状态已重置')));
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.clear_all),
                  title: const Text('重置文件哈希缓存'),
                  subtitle: const Text('清除文件重复检测缓存，重新检测所有文件'),
                  onTap: () {
                    Navigator.pop(context);
                    _resetHashCache();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.delete_sweep),
                  title: const Text('重置备份数据'),
                  subtitle: const Text('清除所有备份相关的数据库和缓存'),
                  onTap: () {
                    Navigator.pop(context);
                    _resetBackupData();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.settings),
                  title: const Text('API设置'),
                  subtitle: const Text('配置自定义API服务器地址'),
                  onTap: () {
                    Navigator.pop(context);
                    _showApiSettingsDialog();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.info_outline),
                  title: const Text('打印调试信息'),
                  subtitle: const Text('在控制台输出当前上传状态信息'),
                  onTap: () {
                    Navigator.pop(context);
                    _printDebugInfo();
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('已在控制台输出调试信息')),
                    );
                  },
                ),
              ],
            ),
          ),
    );
  }

  // 打印调试信息
  Future<void> _printDebugInfo() async {
    debugPrint('====== 传输列表 - 调试信息 ======');

    // 打印相册缓存信息
    final backupState = ref.read(photoBackupProvider);
    final selectedAlbumInfos =
        backupState.albumCache
            .where((album) => backupState.selectedAlbums[album.id] == true)
            .toList();

    debugPrint(
      '相册缓存: 总数量=${backupState.albumCache.length}，已选中=${selectedAlbumInfos.length}',
    );

    // 列出所有选中的相册和其文件数量
    debugPrint('选中相册列表:');
    for (int i = 0; i < selectedAlbumInfos.length; i++) {
      final album = selectedAlbumInfos[i];
      debugPrint(
        '${i + 1}. ${album.name}: 照片=${album.imageCount}，视频=${album.videoCount}',
      );
    }

    // 打印上传任务状态
    final tasks = ChunkUploadService.uploadTasks;
    debugPrint('上传任务总数: ${tasks.length}');

    // 按状态分类任务
    final pendingTasks =
        tasks.where((task) => task.status == UploadTaskStatus.pending).toList();
    final uploadingTasks =
        tasks
            .where((task) => task.status == UploadTaskStatus.uploading)
            .toList();
    final pausedTasks =
        tasks.where((task) => task.status == UploadTaskStatus.paused).toList();
    final completedTasks =
        tasks
            .where((task) => task.status == UploadTaskStatus.completed)
            .toList();
    final failedTasks =
        tasks.where((task) => task.status == UploadTaskStatus.failed).toList();
    final canceledTasks =
        tasks
            .where((task) => task.status == UploadTaskStatus.canceled)
            .toList();

    debugPrint('待上传任务: ${pendingTasks.length}');
    debugPrint('上传中任务: ${uploadingTasks.length}');
    debugPrint('已暂停任务: ${pausedTasks.length}');
    debugPrint('已完成任务: ${completedTasks.length}');
    debugPrint('失败任务: ${failedTasks.length}');
    debugPrint('已取消任务: ${canceledTasks.length}');

    // 打印失败任务的详细信息
    if (failedTasks.isNotEmpty) {
      debugPrint('失败任务详情:');
      for (int i = 0; i < failedTasks.length; i++) {
        final task = failedTasks[i];
        debugPrint('${i + 1}. ${task.fileName}');
        debugPrint('   - 错误: ${task.error ?? "无错误信息"}');
        debugPrint('   - 路径: ${task.filePath}');
        debugPrint('   - 大小: ${task.formattedSize}');
      }
    }

    // 打印正在上传的任务进度
    if (uploadingTasks.isNotEmpty) {
      debugPrint('上传中任务进度:');
      for (int i = 0; i < uploadingTasks.length; i++) {
        final task = uploadingTasks[i];
        debugPrint(
          '${i + 1}. ${task.fileName}: ${task.progress.toStringAsFixed(1)}%',
        );
      }
    }

    // 打印自动备份设置
    debugPrint('自动备份设置:');
    debugPrint('最大并行备份数: ${backupState.parallelBackupCount}');
    debugPrint('备份照片: ${backupState.autoBackupPhotos ? "是" : "否"}');
    debugPrint('备份视频: ${backupState.autoBackupVideos ? "是" : "否"}');

    final photoBackupService = PhotoBackupService();
    debugPrint('备份服务状态: ${photoBackupService.isBackingUp ? "正在备份" : "未在备份"}');

    debugPrint('====== 调试信息结束 ======');
  }

  // 重置文件哈希缓存
  Future<void> _resetHashCache() async {
    // 确认对话框
    final confirmed =
        await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('确认重置'),
                content: const Text('此操作将清除文件重复检测缓存，允许重新检测所有文件。是否继续？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    style: TextButton.styleFrom(foregroundColor: Colors.red),
                    child: const Text('确定重置'),
                  ),
                ],
              ),
        ) ??
        false;

    if (!confirmed) return;

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在重置文件哈希缓存...'),
              ],
            ),
          ),
    );

    try {
      final photoBackupService = PhotoBackupService();
      // 仅重置文件哈希服务
      await photoBackupService.resetFileHashCache();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示成功对话框
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('文件哈希缓存已重置')));
      }

      // 刷新界面
      setState(() {
        _activeStreamKey = UniqueKey();
      });
    } catch (e) {
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示错误对话框
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('重置失败: $e')));
      }
    }
  }

  // 重置备份数据
  Future<void> _resetBackupData() async {
    // 确认对话框
    final confirmed =
        await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('确认重置'),
                content: const Text('此操作将清除所有备份相关的数据库和缓存，包括上传记录和文件哈希信息。是否继续？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    style: TextButton.styleFrom(foregroundColor: Colors.red),
                    child: const Text('确定重置'),
                  ),
                ],
              ),
        ) ??
        false;

    if (!confirmed) return;

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在重置所有备份数据...'),
              ],
            ),
          ),
    );

    try {
      final photoBackupService = PhotoBackupService();
      // 清理所有备份相关数据
      await photoBackupService.cleanupBackupData();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示成功对话框
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('备份数据已全部重置')));
      }

      // 刷新界面
      setState(() {
        _activeStreamKey = UniqueKey();
        _completedStreamKey = UniqueKey();
      });
    } catch (e) {
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示错误对话框
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('重置失败: $e')));
      }
    }
  }

  // 显示API设置对话框
  void _showApiSettingsDialog() async {
    try {
      // 获取当前配置
      final photoBackupService = PhotoBackupService();

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('当前版本暂不支持修改API设置，请前往上传详情页面修改')),
      );

      // 转到上传详情页面
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const UploadDetailPage()),
      );
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('加载API设置失败: $e')));
    }
  }
}
